package com.crawler.waf.utils;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import com.crawler.waf.config.WafProperties;

/**
 * 自定义缓存管理
 * @author rubekid
 * @date 2016年11月11日
 * @param <T>
 * @param <PK>
 */
public class EhCacheManager {
	
    private final static String EHCACHE_NAME = WafProperties.getProperty("ehcache.name");
    
    /**
     * cache管理器
     */
    private final static CacheManager cacheManager = SpringContextUtil.getBean(CacheManager.class);
	
	private String prefix = "";
	
	/**
	 * 缓存名称
	 */
	private String ehcacheName;
	
	public EhCacheManager(){
		ehcacheName = EHCACHE_NAME;
	}
	
	public EhCacheManager(String prefix){
		this.prefix = prefix;
	}
	
	public EhCacheManager(String ehcacheName, String prefix){
		this.ehcacheName = ehcacheName;
		this.prefix = prefix;
	}
    
    /**
	 * 返回缓存
	 */
	public <T> T  get(String key, Class<T> clazz){
		Cache cache = cacheManager.getCache(ehcacheName);
		key = prefix + key;
        Cache.ValueWrapper value = cache.get(key);
        if (value == null) {
            return null;
        }
        return (T) value.get();
	}
    
    /**
     * 设置缓存
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        Cache cache = cacheManager.getCache(ehcacheName);
        if(value!=null){
        	key = prefix + key;
            cache.put(key, value);
        }
    }
}